<template>
  <div class="container" style="padding: 20px;">
    <div class="app-container" style="padding: 20px;height: 500px;position: relative;">
      <el-button type="primary" size="mini" style="margin-bottom: 10px;" @click="dialogVisible=true">添加角色</el-button>
      <el-table
         v-loading="loading"
        :stripe="true"
        :border="true"
        style="width: 1300px;box-sizing: border-box;"
        :data="data.rows"
        >
        <el-table-column
          type="index"
          label="序号"
          width="80">
        </el-table-column>
        <el-table-column
          label="角色"
          width="200"> 
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" size="mini" v-model="scope.row.name"></el-input>
            <span v-else>{{ scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="启用"
          width="219">
            <template slot-scope="scope">
              <el-switch
                v-if="scope.row.isEdit"
                @change="switchItem(scope.row)"
                :value="scope.row.state==1?true:false">
              </el-switch>
              <span v-else>{{ scope.row.state==1?'已启用':'未启用' }}</span>
            </template>
        </el-table-column>
        <el-table-column
          label="描述"
          width="400">
          <template slot-scope="scope">
            <el-input  type="textarea" :rows="2"  v-model="scope.row.description" v-if="scope.row.isEdit" size="mini"></el-input>
            <span v-else>{{ scope.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column
          width="400"
          label="操作">
          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
              <el-button size="mini" type="primary" @click="editSubmit(scope.row)">确定</el-button>
              <el-button size="mini" @click="editCancel(scope.row)">取消</el-button>
            </div>
            <div v-else>
              <el-button
              size="mini"
              type="primary"
              @click="assignPermissions(scope.row.id)">分配权限</el-button>
            <el-button
              size="mini"
              @click="handleEdit(scope.row.id)">编辑</el-button>
            <el-popconfirm
              @onConfirm="handleDelete(scope.row)"
              style="margin-left: 10px;"
                title="你确定要删除这个角色吗？"
              >
                <el-button
                slot="reference"
                size="mini"
                type="danger">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        background
        :page-size="5"
        :current-page.sync="page"
        @current-change="handleCurrentChange"
        layout="prev, pager, next"
        class="pagg"
        :total="data.total">
      </el-pagination>
    </div>

    <!-- 新增角色 -->
    <el-dialog
      title="新增角色"
      :visible.sync="dialogVisible"
      width="30%">
      <el-form :inline="true" label-width="120px" :model="formData" :rules="rules" ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input size="mini" style="width: 270px;" v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="启用">
          <el-switch
            @change="switchChange"
            v-model="value"
            >
          </el-switch>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input type="textarea" :rows="3" style="width: 270px;" v-model="formData.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel" size="mini">取 消</el-button>
        <el-button type="primary" @click="addSubmit" size="mini">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="assign" 
      width="50%">
      <el-tree :data="permissions" :props="defaultProps" 
      show-checkbox :default-expand-all="true"
      node-key="id" :default-checked-keys="checkedKey"
      :check-strictly="true" @check="checkChange">

      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assign = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="assignPsn" size="mini">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {getRole,addRole,updateRole,deleteRole,getDetailRole,assignRolePermissions} from '@/api/role'
import {getPermissions} from '@/api/permissions'
import {transListToTreeData} from '@/utils/index'
export default {
  name: 'Role',
  data() {
    return {
      data:{},
      page:1,
      pageSize:5,
      loading:false,
      dialogVisible:false,
      assign:false,
      value:false,
      permissions:[],
      defaultProps:{
        children: 'children',
        label: 'name'
      },
      checkedKey:[],
      roleId:'',
      formData:{
        name:'',
        description:'',
        state:0
      },
      rules:{
        name:[
        { required: true, message: '角色名称不能为空', trigger: 'blur' },
        ],
        description:[
        { required: true, message: '角色描述不能为空', trigger: 'blur' },
        ]
      }
    }
  },
  async created() {
    await this.init()
    const data=await getPermissions()
    this.permissions=transListToTreeData(data,0)
  },
  methods:{
    async init() {
      this.loading=true
      const result=await getRole({page:this.page,pagesize:this.pageSize})
      result.rows.forEach(item=>{
      item.isEdit=false
      // 行内编数据缓存
      // item.editRow={...item}
      this.$set(item,'editRow',{
        name:item.name,
        state:item.state,
        description:item.description
      })
    })
      this.data=result
      this.loading=false
    },
    async handleCurrentChange() {
      await this.init()
  },
  switchChange(val) {
    val?this.formData.state=1:this.formData.state=0
  },
  // 添加角色
  async addSubmit() {
    await this.$refs.addForm.validate()
    await addRole(this.formData)
    this.dialogVisible=false
    this.page=Math.ceil((++this.data.total)/this.pageSize)
    await this.$refs.addForm.resetFields()
    await this.init()
    this.$message({
      message: '角色添加成功',
      type: 'success'
    });
  },
  async cancel() {
    await this.$refs.addForm.resetFields()
    this.dialogVisible = false
  },
  switchItem(item) {
    item.state==1?item.state=0:item.state=1
  },
  // 编辑确认
  async editSubmit(item) {
    if(item.name&&item.description) {
      await updateRole(item.id,item)
      // 更新缓存
      this.$set(item,'editRow',{
        name:item.name,
        state:item.state,
        description:item.description
      })
      this.$message({
        type:'success',
        message:'角色更新成功'
      })
      item.isEdit=false
    }
    else {
      this.$message({
        type:'warning',
        message:'角色和描述不能为空!'
      })
    }
  },
  // 编辑取消
  editCancel(item) {
    item.name=item.editRow.name
    item.description=item.editRow.description
    item.state=item.editRow.state
    item.isEdit=false
  },
  handleEdit(id) {
    this.data.rows.filter((item)=>{
      if(item.id==id) {
        return item.isEdit=true
      }
    })
  },
  // 删除
  async handleDelete(row) {
    await deleteRole(row.id)
    // 改变页数
    this.page=Math.ceil((--this.data.total)/this.pageSize)
    await this.init()
    this.$message({
      type:'success',
      message:'角色删除成功'
    })
  },
  // 分配权限
  async assignPermissions(id) {
    // 获取角色对应的权限
    const data=await getDetailRole(id)
    this.roleId=id
    this.checkedKey=data.permIds
    this.assign=true
  },
  // 树节点发生变化
  checkChange(checkNode,node) {
    this.checkedKey=node.checkedKeys
  },
  // 确认分配权限
  async assignPsn() {
    const data={
      id:this.roleId,
      permIds:this.checkedKey
    }
    await assignRolePermissions(data)
    this.$message({
      type:'success',
      message:'角色分配权限成功'
    })
    this.assign=false
  }
  },
}
</script>
<style lang="scss" scoped>
.pagg {
  display: inline-block;
  position: relative;
  left: 50%;
  bottom: -50px;
  transform: translateX(-50%);
}
</style>